package com.example.springbootdemo.config;

import com.example.springbootdemo.bean.entity.User;
import com.example.springbootdemo.exception.BusinessErrorException;
import com.example.springbootdemo.exception.BusinessResponseEnum;
import com.example.springbootdemo.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * UserDetailsService是需要实现的登录用户查询的service接口，实现loadUserByUsername()方法
 * 从数据库中根据用户查询用户的详细信息，包括权限
 * @author hh
 * @date 2022/1/27
 */
@Slf4j
@Component
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private IUserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 通过userName获取用户信息
        List<User> userList = userService.getUserByUserName(username);
        if (CollectionUtils.isEmpty(userList)){
            throw new UsernameNotFoundException("用户不可用");
        }
        if (userList.size() > 1){
            throw new BusinessErrorException(BusinessResponseEnum.DATA_EXCEPTION);
        }
        User user = userList.get(0);
        // 定义权限列表
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        // 用户可以访问的资源名称（或者说用户所拥有的权限） 注意：必须"ROLE_"开头
        grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_admin"));
//        List<GrantedAuthority> grantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList("admin,ROLE_sale");
        return new org.springframework.security.core.userdetails.User(user.getName(), user.getPassword(), grantedAuthorities);
    }

}
